package org.springframework.web.filter;

import top.malaoshi.util.StringUtil;
import top.malaoshi.web.utils.StaticFileAndDirectory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class CharacterEncodingFilter implements Filter {

    private String charset = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String encoding = filterConfig.getInitParameter("encoding");
        if(!StringUtil.isEmpty(encoding)){
            this.charset = encoding;
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain fc) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse)servletResponse;

        boolean b= StaticFileAndDirectory.is(req);
        if(b) {
            fc.doFilter(req,resp);
            return;
        }

        req.setCharacterEncoding(charset);
        resp.setCharacterEncoding(charset);
        // 有 resp.setCharacterEncoding(charset) 代码，就不需要下面代码
//        resp.setContentType("text/html; charset="+charset);
        fc.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }


}